<?php

// Copyright 2019 Hackware SpA <human@hackware.cl>
// "Hackware Web Services Core" is released under the MIT License terms.

namespace Hawese\Tests;

use Hawese\Core\User;
use Laravel\Lumen\Testing\DatabaseTransactions;

class AuthControllerTest extends TestCase
{
    use DatabaseTransactions;

    public function setUp(): void
    {
        parent::setUp();

        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';

        $this->user = new User([
            'uid' => 'username',
            'email' => 'mail@doma.in'
        ]);
        $this->user->changePassword('password');
        $this->user->insert();
    }

    public function testSignupWithEmail()
    {
        $token = $this->user->generateSystemToken();
        $response = $this->request(
            'POST',
            '/auth/signup',
            ['uid' => 'username1', 'email' => 'email@example.com'],
            ['Authorization' => "Bearer $token->key:$token->secret" ]
        );
        $this->assertSame('username1', $response->getData()->uid);
        $this->assertSame('email@example.com', $response->getData()->email);
    }

    public function testSignupWithUidAsEmail()
    {
        $token = $this->user->generateSystemToken();
        $response = $this->request(
            'POST',
            '/auth/signup',
            ['uid' => 'email@example.com'],
            ['Authorization' => "Bearer $token->key:$token->secret" ]
        );
        $this->assertSame('email@example.com', $response->getData()->uid);
    }

    public function testSignupWithReturnToken()
    {
        $token = $this->user->generateSystemToken();
        $response = $this->request(
            'POST',
            '/auth/signup',
            ['uid' => 'email@example.com', 'return_token' => 'porfa'],
            ['Authorization' => "Bearer $token->key:$token->secret" ]
        );
        $this->assertObjectHasAttribute('secret', $response->getData());
    }

    public function testLoginWithUid()
    {
        $this->assertFalse($this->user->amI());

        $response = $this->request(
            'POST',
            '/auth/login',
            ['username' => $this->user->uid, 'password' => 'password']
        );

        $this->assertSame(
            $this->user->uid,
            $response->getData()->uid
        );
        $this->assertTrue($this->user->amI());
    }

    public function testLoginWithEmail()
    {
        $this->assertFalse($this->user->amI());

        $response = $this->request(
            'POST',
            '/auth/login',
            ['username' => $this->user->email, 'password' => 'password']
        );

        $this->assertSame(
            $this->user->uid,
            $response->getData()->uid
        );
        $this->assertTrue($this->user->amI());
    }

    public function testLoginWrongUsername()
    {
        $response = $this->request(
            'POST',
            '/auth/login',
            ['username' => 'anything', 'password' => 'password']
        );
        $this->assertStringContainsString(
            'could not be found',
            $response->getData()->error->message
        );
    }

    public function testLoginWrongPassword()
    {
        $response = $this->request(
            'POST',
            '/auth/login',
            ['username' => $this->user->email, 'password' => 'not_password']
        );
        $this->assertStringContainsString(
            'Wrong',
            $response->getData()->error->message
        );
    }

    public function testLoginNoInput()
    {
        $response = $this->request(
            'POST',
            '/auth/login',
        );
        $this->assertStringContainsString(
            'invalid',
            $response->getData()->error->message
        );
    }

    public function testEmailTokenWithUid()
    {
        $this->validOrigin();
        $response = $this->request(
            'POST',
            '/auth/email-token',
            ['username' => $this->user->uid],
            ['Referer' => $this->validOrigin()]
        );
        $this->assertSame(
            'm**l@doma.in',
            $response->getData()->To[0][0]
        );
    }

    public function testEmailTokenWithEmail()
    {
        $this->validOrigin();
        $response = $this->request(
            'POST',
            "/auth/email-token?origin_url={$this->validOrigin()}",
            ['username' => $this->user->email]
        );
        $this->assertSame(
            'm**l@doma.in',
            $response->getData()->To[0][0]
        );
    }

    public function testEmailTokenWrongUsername()
    {
        $response = $this->request(
            'POST',
            '/auth/email-token',
            ['username' => 'not_username'],
            ['Referer' => $this->validOrigin()]
        );
        $this->assertStringContainsString(
            'could not be found',
            $response->getData()->error->message
        );
    }

    public function testEmailTokenNoInput()
    {
        $response = $this->request(
            'POST',
            '/auth/email-token',
            [],
            ['Referer' => $this->validOrigin()]
        );
        $this->assertStringContainsString(
            'invalid',
            $response->getData()->error->message
        );
    }

    public function testWhoAmI()
    {
        $this->user->login();
        $this->assertSame(
            $this->user->uid,
            $this->request('GET', '/auth/whoami')->getData()->uid
        );
    }

    public function testUnauthorizedWhoAmI()
    {
        $this->assertSame(
            \Illuminate\Http\Response::HTTP_UNAUTHORIZED,
            $this->request('GET', '/auth/whoami')->getStatusCode()
        );
    }

    public function testLogout()
    {
        $this->user->login();
        $this->assertTrue($this->user->amI());
        $this->assertSame(
            'true',
            $this->request('POST', '/auth/logout')->getContent()
        );
        $this->assertFalse($this->user->amI());
    }

    // AuthServiceProvider tests, use /auth/whoami so I'll leave it here

    public function testLoginWithCookie()
    {
        $token = $this->user->generateHumanToken();
        $response = $this->call(
            'GET',
            '/auth/whoami',
            [],
            ['auth_token' => "$token->key:$token->secret"]
        );
        $this->assertSame($this->user->uid, $response->getData()->uid);
    }

    public function testLoginWithToken()
    {
        $token = $this->user->generateHumanToken();
        $response = $this->request(
            'GET',
            '/auth/whoami',
            [],
            ['Authorization' => "Bearer $token->key:$token->secret"]
        );
        $this->assertSame($this->user->uid, $response->getData()->uid);
    }

    public function testLoginWithInput()
    {
        $token = $this->user->generateHumanToken();
        $response = $this->request(
            'GET',
            "/auth/whoami?auth_token=$token->key:$token->secret"
        );
        $this->assertSame($this->user->uid, $response->getData()->uid);
    }

    public function testLoginWrongUid()
    {
        app('session')->set('user_uid', 'nope');
        $response = $this->request(
            'GET',
            '/auth/whoami',
        );
        $this->assertSame('Unauthorized.', $response->getData());
    }

    public function testLoginAsSuperUser()
    {
        // Does not really belong here. But IDK where to write this test.
        $this->assertFalse(app('gate')->allows('anything-and-everything'));
        $this->user->uid = 'hawese';
        $this->user->update();
        app('session')->set('user_uid', $this->user->uid);
        $this->assertTrue(app('gate')->allows('anything-and-everything'));
    }
}
